import jieba.analyse
import pymysql

import sys

import sys

arg1 = 0
if len(sys.argv) > 1:
    arg1 = sys.argv[1]

if arg1:
    arg_str = " where id = %s " % str(arg1)
else:
    arg_str = ''

# 连接数据库
conn = pymysql.connect(host='localhost',
user='root',
password='root',
db='v3u',
charset='utf8')
# 创建一个游标
cursor = conn.cursor()

sql = "select id,title from article %s order by id desc limit 1 " % arg_str
cursor.execute(sql)
datalist = cursor.fetchall()
for data in datalist:
    tags = jieba.analyse.extract_tags(data[1])
    for t in tags:
        try:
            sql = "insert into tags(name) values ('%s') " % str(t)
            cursor.execute(sql)
            conn.commit()
        except Exception as e:
            print(str(e))

    strs = ",".join("'%s'" % tag for tag in tags)
    sql = "select id from tags where name in ("+strs+");"
    cursor.execute(sql)
    taglist = cursor.fetchall()
    for tag in taglist:
        try:
            sql = "insert into links(tag_id,a_id) values (%s,%s) " % (tag[0],data[0])
            cursor.execute(sql)
            conn.commit()
        except Exception as e:
            print(str(e))
            pass

cursor.close()
conn.close()